<template>
  <view class="search-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input 
          type="text" 
          v-model="keyword" 
          placeholder="输入标题关键词搜索" 
          placeholder-class="placeholder"
          @input="handleInput"
          confirm-type="search"
          @confirm="doSearch(true)"
        />
        <view 
          class="clear-btn" 
          v-if="keyword" 
          @click="clearKeyword"
        >
          <uni-icons type="clear" size="18" color="#999"></uni-icons>
        </view>
      </view>
      <text class="cancel-btn" @click="handleCancel">{{ isSearching ? '取消' : '返回' }}</text>
    </view>

    <!-- 搜索内容 -->
    <scroll-view 
      class="search-content" 
      scroll-y
      @scrolltolower="loadMore"
      :scroll-with-animation="true"
    >
      <!-- 历史记录 -->
      <view class="history-section" v-if="!keyword && searchHistory.length">
        <view class="section-header">
          <text class="title">历史搜索</text>
          <uni-icons 
            type="trash" 
            size="20" 
            color="#999" 
            @click="showClearConfirm"
          ></uni-icons>
        </view>
        <view class="history-tags">
          <view 
            class="tag" 
            v-for="(item, index) in searchHistory" 
            :key="index"
            @click="quickSearch(item)"
          >
            {{ item }}
            <uni-icons 
              type="close" 
              size="14" 
              color="#ccc" 
              @click.stop="removeHistory(index)"
            />
          </view>
        </view>
      </view>

      <!-- 热门推荐 -->
      <view class="hot-section" v-if="!keyword">
        <view class="section-header">
          <text class="title">热门搜索</text>
          <uni-icons 
            type="reload" 
            size="20" 
            color="#999" 
            @click="loadHotKeywords"
          />
        </view>
        <view class="hot-tags">
          <view 
            class="tag" 
            v-for="(item, index) in hotList" 
            :key="index"
            @click="quickSearch(item)"
          >
            <text class="hot-index">{{ index + 1 }}</text>
            {{ item }}
          </view>
        </view>
      </view>

      <!-- 搜索结果 -->
      <view class="result-section" v-else>
        <view 
          class="result-item" 
          v-for="item in searchResults" 
          :key="item.id"
          @click="gotoDetail(item.id)"
        >
          <image 
            :src="item.cover" 
            class="cover-image"
            mode="aspectFill"
          />
          <view class="content">
            <text class="title">{{ item.title }}</text>
            <view class="meta">
              <text class="author">{{ item.author }}</text>
              <text class="time">{{ item.publishTime | formatTime }}</text>
            </view>
            <text class="desc">{{ item.content | contentPreview }}</text>
          </view>
        </view>

        <uni-load-more 
          :status="loadStatus"
          :contentText="{
            contentdown: '上拉加载更多',
            contentrefresh: '正在加载',
            contentnomore: '没有更多了'
          }"
        />

        <view 
          class="no-data" 
          v-if="searchResults.length === 0 && !loading"
        >
          <uni-icons type="search" size="48" color="#ccc" />
          <text class="empty-text">未找到相关结果</text>
        </view>
      </view>
    </scroll-view>

    <!-- 清除确认弹窗 -->
    <uni-popup ref="clearPopup" type="dialog">
      <uni-popup-dialog
        mode="base"
        type="error"
        title="确认清除"
        content="确定要清空所有历 史记录吗？"
        @confirm="clearHistory"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
      searchHistory: [],
      hotList: [],
      searchResults: [],
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      loadStatus: 'more',
      loading: false,
      debounceTimer: null
    }
  },
  computed: {
    isSearching() {
      return this.keyword || this.searchResults.length > 0
    }
  },
  onLoad() {
    this.loadHistory()
    this.loadHotKeywords()
  },
  methods: {
    // 加载历史记录
    async loadHistory() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8088/api/search/history',
          method: 'GET',
          header: {
            'X-User-Id': this.getUserId() // 从全局状态获取用户ID
          }
        })
        if (res.statusCode === 200) {
          this.searchHistory = res.data.data || []
        }
      } catch (e) {
        uni.showToast({ title: '历史记录加载失败', icon: 'none' })
      }
    },

    // 加载热门关键词
    async loadHotKeywords() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8088/api/keyword/hot',
          method: 'GET',
          data: { top: 10 }
        })
        if (res.statusCode === 200) {
          this.hotList = res.data.data || []
        }
      } catch (e) {
        uni.showToast({ title: '热门搜索加载失败', icon: 'none' })
      }
    },

    // 输入处理
    handleInput() {
      clearTimeout(this.debounceTimer)
      this.debounceTimer = setTimeout(() => {
        if (this.keyword.trim()) {
          this.doSearch(true)
        }
      }, 500)
    },

    // 执行搜索
    async doSearch(isNew) {
      if (this.loading) return
      
      this.loading = true
      this.loadStatus = 'loading'

      try {
        if (isNew) {
          this.pagination.page = 1
          this.searchResults = []
          await this.saveHistory()
        }

        // 执行搜索请求
        const res = await uni.request({
          url: 'http://localhost:8088/api/articles/search',
          method: 'GET',
          data: {
            keyword: this.keyword,
            page: this.pagination.page,
            size: this.pagination.size
          }
        })

        if (res.statusCode === 200) {
          const data = res.data.data
          this.searchResults = [...this.searchResults, ...data.list]
          this.pagination.total = data.total
          
          this.loadStatus = data.list.length < this.pagination.size ? 'noMore' : 'more'
          if (isNew) this.pagination.page = 1
        }
      } catch (e) {
        this.loadStatus = 'more'
        uni.showToast({ title: '搜索失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    // 保存历史记录
    async saveHistory() {
      const keyword = this.keyword.trim()
      if (!keyword) return

      try {
        await uni.request({
          url: '/api/search/history',
          method: 'POST',
          header: {
            'X-User-Id': this.getUserId()
          },
          data: { keyword }
        })
        this.loadHistory() // 刷新历史记录
      } catch (e) {
        console.error('保存失败:', e)
      }
    },

    // 加载更多
    loadMore() {
      if (this.loadStatus === 'noMore' || this.loading) return
      this.pagination.page++
      this.doSearch(false)
    },

    // 快速搜索
    quickSearch(keyword) {
      this.keyword = keyword
      this.doSearch(true)
    },

    // 清除关键词
    clearKeyword() {
      this.keyword = ''
      this.searchResults = []
    },

    // 取消/返回
    handleCancel() {
      if (this.isSearching) {
        this.clearKeyword()
      } else {
        uni.navigateBack()
      }
    },

    // 显示清除确认
    showClearConfirm() {
      this.$refs.clearPopup.open()
    },

    // 清空历史记录
    async clearHistory() {
      try {
        await uni.request({
          url: 'http://localhost:8088/api/search/history',
          method: 'DELETE',
          header: {
            'X-User-Id': this.getUserId()
          }
        })
        this.searchHistory = []
      } catch (e) {
        uni.showToast({ title: '清除失败', icon: 'none' })
      }
    },

    // 删除单个历史记录
    async removeHistory(index) {
      try {
        const keyword = this.searchHistory[index]
        await uni.request({
          url: `http://localhost:8088/api/search/history/${encodeURIComponent(keyword)}`,
          method: 'DELETE',
          header: {
            'X-User-Id': this.getUserId()
          }
        })
        this.searchHistory.splice(index, 1)
      } catch (e) {
        uni.showToast({ title: '删除失败', icon: 'none' })
      }
    },

    // 获取用户ID（根据实际项目调整）
    getUserId() {
      return uni.getStorageSync('userId') || 'default'
    }
  },
  filters: {
    formatTime(val) {
      return val ? val.split(' ')[0] : ''
    },
    contentPreview(val) {
      const text = val.replace(/<[^>]+>/g, '')
      return text.length > 60 ? text.substr(0, 60) + '...' : text
    }
  }
}
</script>

<style lang="scss" scoped>
.search-container {
  background: #fff;
  height: 100vh;
}

.search-bar {
  padding: 16rpx 32rpx;
  display: flex;
  align-items: center;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

  .search-input {
    flex: 1;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 32rpx;
    display: flex;
    align-items: center;
    
    input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      margin: 0 24rpx;
    }
  }
  
  .cancel-btn {
    font-size: 30rpx;
    color: #333;
    margin-left: 24rpx;
  }
}

.history-section, .hot-section {
  padding: 32rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

.history-tags, .hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  
  .tag {
    padding: 12rpx 32rpx;
    background: #f5f5f5;
    border-radius: 40rpx;
    font-size: 26rpx;
    color: #666;
    display: flex;
    align-items: center;
    
    .hot-index {
      color: #ff5500;
      margin-right: 8rpx;
    }
  }
}

.result-section {
  padding: 24rpx;
  
  .result-item {
    padding: 24rpx 0;
    border-bottom: 1rpx solid #eee;
    display: flex;
    
    .cover-image {
      width: 200rpx;
      height: 140rpx;
      border-radius: 8rpx;
      margin-right: 24rpx;
    }
    
    .content {
      flex: 1;
      
      .title {
        font-size: 30rpx;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        line-height: 1.4;
      }
      
      .meta {
        margin: 16rpx 0;
        color: #999;
        font-size: 24rpx;
      }
      
      .desc {
        font-size: 26rpx;
        color: #666;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        line-height: 1.4;
      }
    }
  }
}

.no-data {
  padding: 120rpx 0;
  text-align: center;
  
  .empty-text {
    color: #999;
    margin-top: 24rpx;
    display: block;
  }
}
</style>
